#!/usr/bin/python
# -*- coding: utf-8 -*-

#Copyright (C) 2011 Daniele Simonetti
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

### UBUNTUONE (DESKTOPCOUCH) BACKEND ###

from desktopcouch.records.server import CouchDatabase
from desktopcouch.records.record import Record as CouchRecord 

COUCH_SHOW_TYPE = "http://epes/couch/show"

class UbuntuOneBusiness:
    def __init__(self):
        self.db = None 
    
    def create_db(self):   
        def define_views_():
            show_id = """function(doc) { 
                emit(doc.showid,doc)
            }"""
            
            self.db.add_view('show_id', show_id, None, 'epes')
         
        try:  
            self.db = CouchDatabase("epes", create=True)
            define_views_()
        except:
            return False
        return True
        
    def insert_show(self, item, order = -1):
    #str(item['showid']), unicode(item['title']), int(item['lastep']), order, int(item['rating'])
        record = CouchRecord( {
            "showid": str(item['showid']),
            "title": unicode(item['title']),
            "lastep": int(item['lastep']),
            "order" : order,
            "rating": int(item['rating']) }, COUCH_SHOW_TYPE)
        try:
            self.db.put_record(record)
        except:
            return False
        return True
        
    def update_show(self, item, order = -1):
        # CHECK IF RECORD EXISTS
        s = self.fetch_show( str(item['showid']) )
        if s is None:
            return self.insert_show(item, order)
        s["title"] = unicode(item['title'])
        s["lastep"] = int(item['lastep'])
        s["order"] = order    
        s["rating"] = int(item['rating'])
        
        try:
            self.db.put_record(record)
        except:
            return False
        return True            

    def remove_show(self, showid):
        # CHECK IF RECORD EXISTS
        s = self.fetch_show( str(item['showid']) )
        if s is None:
            return True
        try:
            self.db.delete_record(s["_id"])
        except:
            return False
        return True
        
    def fetch_all(self):
        result = self.db.execute_view('show_id', 'epes')
        fetched = []        
                
        for r in result:
            s = {}
            got = r.value        
            s['showid'] = got['showid']
            s['title'] = got['title']
            s['lastep'] = got['lastep']
            s['order'] = got['order']
            s['rating'] = got['rating']
            
            fetched.append(s)
        return fetched

    def has_show(self, showid):
        result = self.db.execute_view('show_id', 'epes')
        return showid in result
        
    def fetch_show(self, showid):
        result = self.db.execute_view('show_id', 'epes')
        if showid in result:
            return result[showid]
        return None
    
